(function() {
    var extend = TED.extend,
		EventDispatcher = TED.EventDispatcher,
		Event = TED.Event,
		Overlay = TED.Overlay,
		augmentObject = TED.augmentObject,
		Ajax = TED.SimpleAjax,
		Storage = TED.Storage;
    window.TED["EditorPlugins"] = window.TED["EditorPlugins"] || {};
    window.TED["EditorPlugins"]["Refer"] = Refer;
    function Refer(attrs) {
        attrs = attrs || {};
        augmentObject(attrs, this.constructor.defaultConfig);
        this.config = attrs
    }
    Refer.defaultConfig = {checkDelay: 100,offsetLeft: 1,offsetTop: 18,dataUrl: "/at-sug",uid: null};
    Refer.prototype = {constructor: Refer,disabled: false,boxWrapper: null,init: function(editor) {
            editor.on("keydown", this.onEditorKeydown, this);
            editor.on("keyup", this.onEditorKeyup, this);
            editor.on("click", this.onEditorClick, this);
            editor.on("blur", function() {
                this.hide()
            }, this);
            this.box = new Box(editor.editAreaWrapper);
            this.box.on("select", this.onSelect, this);
            this.data = new Data(this.config.dataUrl, this.config.uid);
            this.data.on("datachange", this.box.update, this.box);
            this.editor = editor
        },destroy: function() {
        },enable: function() {
            this.disabled = false
        },disable: function() {
            this.disabled = true
        },query: function(key) {
            this.data.getData(key)
        },onSelect: function(value) {
            var el = this.editor.getSelectedElement();
            if (value !== null) {
                el.innerHTML = "@" + value
            }
            this.breakMode(32)
        },onEditorKeydown: function(e) {
            if (this.disabled) {
                return
            }
            if (this.box.isShow) {
                switch (e.keyCode) {
                    case 38:
                        this.box.pre();
                        break;
                    case 40:
                        this.box.next();
                        break;
                    case 13:
                        this.onSelect(this.box.getValue());
                        this.box.hide();
                        break;
                    default:
                        return
                }
                if (e.preventDefault) {
                    e.preventDefault()
                } else {
                    e.returnValue = false
                }
                e.exitFunction = true
            }
        },onEditorKeyup: function(e) {
            if (this.disabled) {
                return
            }
            var code = e.keyCode;
            if ((code === 50 && e.shiftKey) || (code === 50 && this.lastUpCode === 16)) {
                this.checkEnterMode()
            }
            var that = this;
            clearTimeout(this.timer);
            this.timer = setTimeout(function() {
                that.checkShowBox()
            }, this.config.checkDelay);
            this.lastUpCode = e.keyCode
        },onEditorClick: function() {
            var that = this;
            clearTimeout(this.timer);
            this.timer = setTimeout(function() {
                that.checkShowBox()
            }, this.config.checkDelay)
        },checkEnterMode: function() {
            var that = this.editor;
            var s = that.getSelection(), r, c;
            if (that.ua.ie ? s.type.toLowerCase() !== "none" : !s.isCollapsed) {
                return
            }
            r = that.getRange();
            if (that.ua.ie) {
                if (this.editor.isEmpty()) {
                    return
                }
                r.moveStart("character", -1);
                r.select();
                c = r.text
            } else {
                var con = r.startContainer, offset = r.startOffset;
                if (con.nodeType === 1 && offset > 0) {
                    con = con.childNodes[offset - 1];
                    offset = con.length
                }
                if (con.nodeType === 3 && offset > 0) {
                    r.setStart(con, offset - 1);
                    s.removeAllRanges();
                    s.addRange(r);
                    c = s.toString()
                }
            }
            var el = that.getSelectedElement();
            if (c === "@" && (el.className !== "at" || el.innerHTML !== "@")) {
                that.execCommand("inserthtml", '<span class="at">@</span>')
            } else {
                if (that.ua.ie) {
                    r.collapse(false);
                    r.select()
                } else {
                    s.collapseToEnd()
                }
            }
        },checkShowBox: function() {
            var el = this.editor.getSelectedElement(), value = el.innerHTML, key;
            if (el.className === "at" && value.charAt(0) === "@") {
                key = value.substring(1).replace(/<br.*>$/i, "");
                if (key.search(/[^\w\u4E00-\u9FA5]/) === -1) {
                    this.show(el.offsetLeft + this.config.offsetLeft - this.editor.editArea.scrollLeft, el.offsetTop + this.config.offsetTop - this.editor.editArea.scrollTop);
                    this.query(key)
                } else {
                    this.hide()
                }
            } else {
                this.hide()
            }
        },hide: function() {
            this.box.hide();
            this.data.getting = null
        },show: function(x, y) {
            this.box.show(x, y)
        },breakMode: function(charcode) {
            var that = this.editor, el = that.getSelectedElement(), node, r;
            if (charcode === 32) {
                node = document.createElement("span");
                node.innerHTML = "&nbsp;";
                node = node.firstChild
            } else {
                node = document.createTextNode(String.fromCharCode(charcode))
            }
            if (el.nextSibling) {
                el.parentNode.insertBefore(node, el.nextSibling)
            } else {
                el.parentNode.appendChild(node)
            }
            if (that.ua.ie) {
                r = document.selection.createRange();
                r.moveEnd("character", 1);
                r.collapse(false);
                r.select()
            } else {
                s = window.getSelection();
                r = document.createRange();
                r.selectNode(node);
                s.removeAllRanges();
                s.addRange(r);
                s.collapseToEnd()
            }
        }};
    function Box(container) {
        Box.superclass.call(this);
        this.container = container;
        this.holder = document.createElement("div");
        this.holder.innerHTML = '<span class="box-title">想用@提到谁？<span>';
        this.holder.className = "box-holder";
        this.holder.style.display = "none";
        this.ul = document.createElement("ul");
        this.ul.className = "box-ul-empty";
        this.holder.appendChild(this.ul);
        container.appendChild(this.holder);
        this.initEvents()
    }
    extend(Box, EventDispatcher, {isShow: false,index: null,length: 0,initEvents: function() {
            var that = this;
            this.bindClick = function() {
                that.onClick.apply(that, arguments)
            };
            this.bindMousedown = function() {
                that.onMousedown.apply(that, arguments)
            };
            Event.addEvent(this.ul, "click", this.bindClick);
            Event.addEvent(this.ul, "mousedown", this.bindMousedown)
        },onMousedown: function(e) {
            if (e.preventDefault) {
                e.preventDefault()
            } else {
                e.returnValue = false
            }
        },onClick: function(e) {
            var target = e.target || e.srcElement;
            if (target.tagName.toLowerCase() === "li") {
                this.fireEvent("select", null, [target.innerHTML]);
                this.hide()
            }
        },update: function(data) {
            if (!this.isShow) {
                return
            }
            if (data.length === 0) {
                this.ul.innerHTML = "";
                this.ul.className = "box-ul-empty"
            } else {
                this.ul.className = "";
                this.ul.innerHTML = '<li unselectable="on">' + data.join('</li><li unselectable="on">') + "</li>"
            }
            this.length = data.length
        },pre: function() {
            if (this.length === 0) {
                return
            }
            if (this.index === null) {
                this.select(this.length - 1)
            } else {
                this.select(this.index === 0 ? this.length - 1 : this.index - 1)
            }
        },next: function() {
            if (this.length === 0) {
                return
            }
            if (this.index === null) {
                this.select(0)
            } else {
                this.select(this.index === this.length - 1 ? 0 : this.index + 1)
            }
        },select: function(index) {
            if (this.index !== null) {
                this.ul.childNodes[this.index].className = ""
            }
            this.ul.childNodes[index].className = "focus";
            this.index = index
        },getValue: function() {
            return this.index !== null ? this.ul.childNodes[this.index].innerHTML : null
        },show: function(x, y) {
            if (this.isShow) {
                if (x === this.x && y === this.y) {
                    return
                } else {
                    this.reset()
                }
            } else {
                this.holder.style.display = "block";
                this.isShow = true
            }
            this.holder.style.left = x + "px";
            this.holder.style.top = y + "px";
            this.x = x;
            this.y = y
        },hide: function() {
            if (!this.isShow) {
                return
            }
            this.reset();
            this.holder.style.display = "none";
            this.isShow = false
        },reset: function() {
            this.ul.innerHTML = "";
            this.length = 0;
            this.ul.className = "box-ul-empty"
        }});
    function Data(url, uid) {
        Data.superclass.call(this);
        this.url = url;
        this.uid = uid
    }
    extend(Data, EventDispatcher, {dataCache: {},queryCache: {},data: null,getData: function(key) {
            if (this.getting === key) {
                return
            }
            this.getting = key;
            if (key === "") {
                this.setData([], true);
                return
            }
            if (this.dataCache[key]) {
                this.setData(this.dataCache[key], true);
                return
            }
            if (this.queryCache[key]) {
                return
            }
            this.queryCache[key] = true;
            var that = this;
            Ajax.get(this.url + "?query=" + encodeURIComponent(key) + "&uid=" + this.uid + "&ie=utf-8", function(data) {
                delete that.queryCache[key];
                data = that.parseData(data);
                that.dataCache[key] = data;
                that.setData(data, key === that.getting)
            }, function(error) {
                delete that.queryCache[key];
                that.fireEvent("error", [error])
            })
        },setData: function(value, need) {
            this.data = value;
            if (need) {
                this.fireEvent("datachange", null, [value])
            }
        },parseData: function(data) {
            try {
                data = eval("(" + data + ")");
                if (data.error === 0) {
                    return data.msg
                } else {
                    throw new Error("服务器返回错误：" + data.error)
                }
            } catch (e) {
                throw new Error("服务器返回数据格式有误！")
            }
        }});
    window.TED["EditorPlugins"]["InsertSmiley"] = InsertSmiley;
    function InsertSmiley(container) {
        this.container = container;
        this.holder = document.createElement("div");
        this.holder.style.position = "relative";
        this.holder.className = "insertsmiley_holder";
        this.overlay = new Overlay(this.holder);
        var that = this;
        Event.addEvent(this.holder, "click", function(e) {
            var target = e.target || e.srcElement;
            if (target === that.holder) {
                that.clickHandler(e)
            }
        });
        this.container.appendChild(this.holder)
    }
    InsertSmiley.prototype = {init: function(editorRef) {
            this.editor = editorRef
        },clickHandler: function() {
            this.overlay.toggle("-320px", "25px", "420px", "355px", "320px", this.editor.config.rootPath + "simplesmiley.html?id=" + this.editor.id, this.holder)
        },closeOverlay: function() {
            this.overlay.close()
        }};
    window.TED["EditorPlugins"]["WordLimit"] = WordLimit;
    function WordLimit(maxNum) {
        this.maxNum = maxNum || 130;
        this.holder = document.createElement("div");
        this.holder.className = "wordlimit-holder";
        this.holder.style.visibility = "hidden"
    }
    WordLimit.prototype = {showLimit: 10,checkTimer: null,checkDelay: 300,isShow: false,exceed: false,init: function(editorRef) {
            this.editor = editorRef;
            this.container = editorRef.wrapper;
            this.container.appendChild(this.holder);
            editorRef.on("keyup", this.handlerEvent, this);
            editorRef.on("focus", this.handlerEvent, this);
            this.check()
        },handlerEvent: function(e) {
            clearTimeout(this.checkTimer);
            var that = this;
            this.checkTimer = setTimeout(function() {
                that.check()
            }, this.checkDelay)
        },check: function(num) {
            var diff = this.maxNum - this.editor.getContentLength();
            if (diff <= this.showLimit) {
                this.holder.style.visibility = "visible";
                this.isShow = true;
                if (diff < 0) {
                    if (!this.exceed) {
                        this.editor.fireEvent("overflow");
                        this.exceed = true
                    }
                    this.holder.innerHTML = '已经超出<span style="font-size:18px;font-family:Arial;color:#f00;">' + -diff + "</span>个字"
                } else {
                    if (this.exceed) {
                        this.editor.fireEvent("unoverflow");
                        this.exceed = false
                    }
                    this.holder.innerHTML = '还能输入<span style="font-size:18px;font-family:Arial;">' + diff + "</span>个字"
                }
            } else {
                if (this.isShow) {
                    this.holder.style.visibility = "hidden";
                    this.isShow = false;
                    if (this.exceed) {
                        this.editor.fireEvent("unoverflow");
                        this.exceed = false
                    }
                }
            }
        }};
    window.TED["EditorPlugins"]["AutoHeightPlugin"] = AutoHeightPlugin;
    function AutoHeightPlugin() {
        this.editorOffsetTop = 0;
        this.editor = null;
        this.editorYdistanceToButton = 200
    }
    AutoHeightPlugin.prototype = {constructor: AutoHeightPlugin,init: function(editor) {
            this.editor = editor;
            editor.enableAutoHeight(this.getEditorMaxHeight());
            editor.on("heightChanged", this.onEditorHeightChanged, this);
            editor.on("focus", this.onEditorFocus, this);
            var that = this;
            if (document.addEventListener) {
                window.addEventListener("resize", function() {
                    that.editor.enableAutoHeight(that.getEditorMaxHeight())
                }, false)
            } else {
                window.attachEvent("onresize", function() {
                    that.editor.enableAutoHeight(that.getEditorMaxHeight())
                })
            }
        },onEditorHeightChanged: function(h, offset) {
            var docScrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
            var docScrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
            if (docScrollTop >= this.editorOffsetTop - 20) {
                return
            }
            window.scrollTo(docScrollLeft, docScrollTop + offset)
        },onEditorFocus: function() {
            this.editorOffsetTop = this.getPageY(this.editor.wrapper)
        },getPageY: function(elem) {
            return elem.offsetParent ? elem.offsetTop + this.getPageY(elem.offsetParent) : elem.offsetTop
        },getEditorMaxHeight: function() {
            var values = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
            values -= this.editorYdistanceToButton;
            return values
        }};
    window.TED["EditorPlugins"]["FilteHtmlPlugin"] = FilteHtmlPlugin;
    function FilteHtmlPlugin(isAutoImage) {
        this.editor = null;
        this.editValidHTML = ["br", "img"];
        this.isAutoImage = isAutoImage === false ? isAutoImage : true;
        this.isFirstTimeImgRec = true;
        this.timer = null;
        this.enable = true
    }
    FilteHtmlPlugin.prototype = {init: function(editor) {
            this.editor = editor;
            if ($.browser.opera === true) {
                return
            }
            editor.on("paste", this.filteHTML, this);
            editor.on("keyup", this.dealWithKeyup, this);
            editor.on("keydown", this.onEditorKeydown, this)
        },onEditorKeydown: function(e) {
            clearTimeout(this.timer);
            if (e.keyCode === 229) {
                this.enable = false
            } else {
                this.enable = true
            }
        },dealWithKeyup: function(e) {
            if (!this.enable) {
                return
            }
            if (this.editor.hasSelection()) {
                return
            }
            var _this = this;
            if (_this.timer) {
                clearTimeout(_this.timer)
            }
            var ev = e || window.event;
            var ctrl_k = (ev.ctrlKey && ev.keyCode == 86);
            _this.timer = setTimeout(function(ctrl_k) {
                _this.preFilte();
                if (!ctrl_k) {
                    _this.autoRecognizeImgUrl()
                }
            }, 100)
        },filteHTML: function(e) {
            e.exitFunction = true;
            var that = this;
            setTimeout(function() {
                that.preFilte();
                if (that.isAutoImage == true) {
                    that.autoRecognizeImgUrl();
                    that.dealWithImages()
                }
            }, 50)
        },createImageTagFromUrl: function(imgurl) {
            var legalImageUrl = '<img src="_LEG_IMG_" class="BDE_Image" onload="TED.EditorCore.ResizeImage(this);" onerror="Stats.sendRequest(\'fr=tb0_forum&st_mod=editor&st_type=urlimagefail&st_value=1\');this.removeAttribute(\'onload\');this.removeAttribute(\'onerror\');" />';
            return legalImageUrl.replace("_LEG_IMG_", imgurl)
        },createVideoFromUrl: function(url) {
            var video_url = '<img width="219" height="174" data-width="500" data-height="450" title="' + url + '" src="/tb/editor/v2/flash.png" class="BDE_Flash"/><br />';
            return video_url
        },classifyUrl: function(s, s_domain, s_name, s_extension) {
            var domain_reg = /(v\.youku\.com)|(www\.tudou\.com)|(v\.ku6\.com)|(www\.56\.com)/gi;
            var result = domain_reg.exec(s_domain);
            if (result == null) {
                return s
            }
            var url = "";
            var name_id = s_name.split("/");
            var video_name = name_id[name_id.length - 1];
            var fail = false;
            switch (result[0]) {
                case "v.youku.com":
                    if (name_id[0] == "v_show") {
                        var name_sp = video_name.split("_");
                        if (name_sp[1]) {
                            url = "http://player.youku.com/player.php/sid/" + name_sp[1] + "/v.swf"
                        } else {
                            fail = true;
                            url = s
                        }
                    } else {
                        fail = true;
                        url = s
                    }
                    break;
                case "www.tudou.com":
                    if (name_id[0] == "programs" && name_id[1] == "view") {
                        url = "http://www.tudou.com/v/" + video_name + "/v.swf"
                    } else {
                        fail = true;
                        url = s
                    }
                    break;
                case "v.ku6.com":
                    if (name_id[0] == "show" || name_id[0] == "special") {
                        url = "http://player.ku6.com/refer/" + video_name + "/v.swf"
                    } else {
                        fail = true;
                        url = s
                    }
                    break;
                case "www.56.com":
                    var first = name_id[0];
                    if (first.search(/^[uw][^\s]+/g) != -1) {
                        url = "http://player.56.com/" + video_name + ".swf"
                    } else {
                        fail = true;
                        url = s
                    }
                    break;
                default:
                    url = s;
                    break
            }
            if (fail) {
                Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlVideoRecFail&st_value=1")
            }
            return url
        },convert_urls: [[/http:\/\/client\.joy\.cn\/flvplayer\/([0-9a-zA-Z]*)_([0-9]*)_[1-9]*_([0-9]*)\.swf$/ig, "http://client.joy.cn/flvplayer/$1_$2_0_$3.swf"], [/http:\/\/www\.letv\.com\/player\/x([0-9a-zA-Z_]*)\.swf$/ig, "http://www.letv.com/player/share/baidu/x$1.swf"], [/http:\/\/www\.kankanews\.com\/object\/kankanewsplayer([0-9a-zA-Z\-\.]*)\.swf/ig, "http://www.kankanews.com/object/kankanewsplayer3.0.swf"], [/http:\/\/www\.m1905\.com\/video\/m\/([0-9]*)\/v\.swf/ig, "http://www.m1905.com/video/s/$1/v.swf?autoplay=0"], [/(http:\/\/share\.vrs\.sohu\.com\/[0-9a-zA-Z_]*\/v\.swf)(\S*)$/ig, "$1&autoplay=false"]],convert: function(url) {
            var s = this.convert_urls;
            for (var i = 0; i < s.length; i++) {
                url = url.replace(s[i][0], s[i][1])
            }
            return url
        },auto_params: [["client.joy.cn", "playstatus", /playstatus=/ig, "0"], ["//v.ifeng.com", "AutoPlay", /AutoPlay=/ig, "false"], ["m1905.com", "autoplay", /autoplay=/ig, "0"], ["kankanews.com", "otherLink", /otherLink=/ig, "false"]],filter_param: function(flash_url_value) {
            if (flash_url_value.indexOf("share.vrs.sohu.com") < 0) {
                flash_url_value = flash_url_value.replace(/(\&)?\w*auto\w*=[\w\d]+/ig, "")
            }
            var ps = this.auto_params;
            for (var i = 0; i < ps.length; i++) {
                var p = ps[i];
                if (flash_url_value.indexOf(p[0]) > -1) {
                    flash_url_value = flash_url_value.replace(p[2], "old_invalid=");
                    flash_url_value += (flash_url_value.indexOf("?") > -1 ? "&" : "?") + p[1] + "=" + p[3]
                }
            }
            return flash_url_value
        },videoUrlRec: function(s, s_domain, s_name, s_extension) {
            var _this = this;
            if (!_this.isWhiteList_video(s)) {
                return s
            }
            if (s_extension == "swf") {
                s = _this.convert(s);
                s = _this.filter_param(s);
                Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlVideoRec&st_value=1");
                return _this.createVideoFromUrl(s)
            }
            var url = _this.classifyUrl(s, s_domain, s_name, s_extension);
            if (url === s) {
                return url
            }
            Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlVideoRec&st_value=1");
            return _this.createVideoFromUrl(url)
        },isWhiteList_video: function(url) {
            var whiteList = this.editor.config.flashWhiteList;
            for (var i = 0, j = whiteList.length; i < j; i++) {
                if (url.indexOf(whiteList[i]) == 0) {
                    return true
                }
            }
            return false
        },dealWithImages: function() {
            this.editor.saveCursor();
            var picsArray = this.editor.editArea.getElementsByTagName("img");
            for (var i = 0; i < picsArray.length; i++) {
                var imgClassName = picsArray[i].className;
                if (imgClassName == "BDE_Image" || imgClassName == "BDE_Smiley" || imgClassName == "BDE_Flash" || imgClassName == "BDE_Music" || imgClassName == "BDE_Empty" || picsArray[i].getAttribute("id") == "editor-tmp-img") {
                    continue
                }
                var newImageTag = document.createElement("img");
                var imgsrc = picsArray[i].getAttribute("src");
                if (!(/\.gif|\.png|\.bmp|\.jpeg|\.jpg$/.test(imgsrc))) {
                    imgsrc += ".gif"
                }
                if (!(/^http/).test(imgsrc)) {
                    imgsrc = "http://" + document.domain + imgsrc
                }
                newImageTag.setAttribute("src", imgsrc);
                newImageTag.className = "BDE_Image";
                newImageTag.setAttribute("onload", "TED.EditorCore.ResizeImage(this)");
                picsArray[i].parentNode.replaceChild(newImageTag, picsArray[i])
            }
            this.editor.ensureCursor()
        },autoRecognizeImgUrl: function() {
            this.editor.saveCursor();
            var _this = this;
            var doubleImgReg = /(?:<img.*?>)|(?:<emb.*?>)|(?:http:\/\/((?:[a-zA-Z\d\-]+\.)+[a-zA-Z\d]+(?:\:[\d]{2,5})?)\/([^\s]+?)\.(jpg|jpeg|gif|png|bmp|html|swf)|(?:http:\/\/(www\.tudou\.com)\/(programs\/view\/[^\s]+?)\/))/gi;
            var editorHtml = this.editor.editArea.innerHTML;
            editorHtml = editorHtml.replace(doubleImgReg, function(s, s_domain, s_name, s_extension, s_tudou, s_tudou_name) {
                if (s.charAt(0) == "<") {
                    return s
                } else {
                    if (s_extension == "swf" || s_extension == "html") {
                        return _this.videoUrlRec(s, s_domain, s_name, s_extension, s_tudou)
                    } else {
                        if (s_tudou == "www.tudou.com") {
                            return _this.videoUrlRec(s, s_tudou, s_tudou_name, s_extension)
                        } else {
                            _this.sendStatistics(1);
                            return _this.createImageTagFromUrl(s)
                        }
                    }
                }
            });
            this.editor.editArea.innerHTML = editorHtml;
            this.editor.ensureCursor()
        },preFilte: function() {
            var _this = this;
            this.editor.saveCursor();
            var content = this.editor.editArea.innerHTML;
            this.editor.editArea.innerHTML = content.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(/<\/ ?tr[^>]*>/gi, "[br]").replace(/<\/ ?td[^>]*>/gi, "&nbsp;&nbsp;").replace(/<(ul|dl|ol)[^>]*>/gi, "[br]").replace(/<(li|dd)[^>]*>/gi, "[br]").replace(/<p [^>]*>/gi, "[br]").replace(new RegExp("<(/?(?:" + this.editValidHTML.join("|") + ")[^>]*)>", "gi"), "[$1]").replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', "gi"), "[span$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:" + this.editValidHTML.join("|") + "|img|span)[^\\]]*)\\]", "gi"), "<$1>");
            if (!$.browser.mozilla) {
                this.editor.editArea.innerHTML = this.editor.editArea.innerHTML.replace(/\r?\n/gi, "<br>")
            }
            this.editor.ensureCursor()
        },sendStatistics: function(type) {
            if (type == 1) {
                Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlimagerec&st_value=1");
                if (this.isFirstTimeImgRec) {
                    this.sendStatistics(3);
                    this.isFirstTimeImgRec = false
                }
            } else {
                if (type == 2) {
                    Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlimagefail&st_value=1")
                } else {
                    if (type == 3) {
                        Stats.sendRequest("fr=tb0_forum&st_mod=editor&st_type=urlimageposts&st_value=1")
                    } else {
                        return
                    }
                }
            }
        }};
    window.TED["EditorPlugins"]["SaveDraft"] = SaveDraft;
    function SaveDraft(uid, forumid, tid, isPb) {
        this.isPb = !!isPb;
        this.key = "d-" + uid + "-" + forumid + "-" + tid
    }
    SaveDraft.prototype = {saveInterval: 5000,timer: null,savedHtml: null,maxNum: 3,storageKey: "tb_editor_storage",init: function(editorRef) {
            if (!Storage.isSupport()) {
                return
            }
            this.editor = editorRef;
            this.initTip();
            this.get();
            var that = this;
            if (editorRef.focused) {
                this.save()
            }
            editorRef.on("blur", function() {
                clearInterval(this.timer)
            }, this);
            editorRef.on("focus", function() {
                this.save()
            }, this);
            editorRef.on("gethtml", function() {
                clearInterval(this.timer);
                this.clearData()
            }, this)
        },save: function() {
            var that = this;
            this.timer = setInterval(function() {
                if (that.savedHtml !== that.editor.editArea.innerHTML) {
                    that.set();
                    that.savedHtml = that.editor.editArea.innerHTML
                }
            }, this.saveInterval)
        },clearData: function() {
            var keys = Storage.get(this.storageKey);
            if (keys === null) {
                return
            }
            keys = keys.split("_");
            for (var i = 0, j = keys.length; i < j; i++) {
                if (keys[i] === this.key) {
                    keys.splice(i, 1);
                    if (keys.length === 0) {
                        Storage.remove(this.storageKey)
                    } else {
                        Storage.set(this.storageKey, keys.join("_"))
                    }
                    Storage.remove(this.key);
                    return
                }
            }
        },set: function() {
            var keys = Storage.get(this.storageKey);
            if (keys === null) {
                Storage.set(this.storageKey, this.key);
                Storage.set(this.key, this.editor.editArea.innerHTML)
            } else {
                keys = keys.split("_");
                var index = this.isInArray(this.key, keys);
                if (index === false) {
                    if (keys.length >= this.maxNum) {
                        Storage.remove(keys.shift())
                    }
                    keys.push(this.key);
                    Storage.set(this.storageKey, keys.join("_"))
                }
                Storage.set(this.key, this.editor.editArea.innerHTML)
            }
            if (this.tip) {
                this.tip.onSave(new Date().getTime())
            }
        },get: function() {
            var content = Storage.get(this.key);
            if (content === null) {
                return
            }
            this.editor.setHtml(content);
            if (this.tip) {
                this.tip.show()
            }
        },isInArray: function(ele, array) {
            for (var i = 0, j = array.length; i < j; i++) {
                if (array[i] === ele) {
                    return i
                }
            }
            return false
        },initTip: function() {
            this.tip = new StorageTip(this, !this.isPb)
        }};
    function StorageTip(storageRef, needBlink) {
        this.storage = storageRef;
        this.needBlink = needBlink === undefined ? true : needBlink;
        this.holder = document.createElement("div");
        this.holder.innerHTML = "你上次未发表的内容已自动恢复";
        this.holder.className = "storageTip";
        this.holder.style.display = "none";
        this.storage.editor.wrapper.appendChild(this.holder)
    }
    StorageTip.prototype = {holder: null,setDateCount: 0,needBlink: true,show: function() {
            if (this.storage.editor.isEmpty()) {
                return
            }
            $(this.holder).fadeIn()
        },onSave: function(date) {
            if (this.storage.editor.isEmpty()) {
                $(this.holder).fadeOut();
                return
            } else {
                this.holder.style.display = "block"
            }
            this.setDate(date)
        },setDate: function(date) {
            this.holder.innerHTML = "你正在输入的内容已自动保存," + new Date(date).toLocaleTimeString();
            if (!this.needBlink) {
                return
            }
            if (this.setDateCount % 5 === 0) {
                $(this.holder).css("backgroundColor", "yellow").animate({backgroundColor: "#efefef"}, 500, function() {
                    this.style.backgroundColor = ""
                })
            }
            this.setDateCount++
        }};
    window.TED["EditorPlugins"]["IdiskPlugin"] = IdiskPlugin;
    function IdiskPlugin(power, fid, max_length, max_size) {
        this.power = power;
        this.fid = fid;
        this.max_length = max_length;
        this.max_size = max_size
    }
    IdiskPlugin.prototype = {buttonId: "idisk_btn",flashCntClassName: "idisk_flash_cnt",flashInited: false,isOtherOpend: false,init: function(editorRef) {
            this.editorRef = editorRef;
            var self = this;
            this.overlay = new IdiskOverlay(editorRef.wrapper, editorRef);
            this.overlay.on("close", function() {
                editorRef.focus()
            });
            editorRef.overlay.on("open", function() {
                if (this.overlay.isOpen) {
                    this.overlay.close()
                }
            }, this);
            this.overlay.on("open", function() {
                if (this.editorRef.overlay.isOpen) {
                    this.editorRef.overlay.close()
                }
            }, this);
            editorRef.toolbar.holder.innerHTML += '<label></label><span class="idisk' + (this.power ? "" : "_disabled") + '" data-cmd="idisk"></span>';
            editorRef.toolbarcmd_idisk = function(el) {
                if (!self.power) {
                    return [false]
                }
                self.overlay.toggle();
                if (!self.flashInited) {
                    $.JsLoadManager.use(editorRef.config.rootPath + "idisk/idisk.js", function() {
                        self.initFlash();
                        self.flashInited = true
                    })
                }
                return [false]
            };
            editorRef.toolbar_hovercmd_idisk = function(el) {
                if (!self.power) {
                    this.hoveroverlay.open("350px", "35px", "290px", "55px", "80px", "http://tieba.baidu.com/tb/editor/v2/picasso/picasso_noright.html?t=201111141108", el)
                }
                return [false]
            };
            editorRef.toolbar_hoverendcmd_idisk = function(el) {
                if (!self.power) {
                    this.hoveroverlay.close()
                }
                return [false]
            }
        },initFlash: function() {
            var btn = this.overlay.uploadBtn;
            this.$flashCnt = $("<div>").css({left: btn.offsetLeft + "px",top: btn.offsetTop + "px",position: "absolute"}).appendTo(btn.offsetParent);
            this.fileUploader = new FileUploader({width: btn.offsetWidth,height: btn.offsetHeight,container: this.$flashCnt[0],UIContainer: this.editorRef.wrapper,url: this.editorRef.config.rootPath + "idisk/FileLoaderPlus.swf"}, {max_length: this.max_length,forum_id: this.fid,upload_size_limit: this.max_size,get_upload_url_url: "http://tieba.baidu.com/disk/getuploadurl"});
            this.fileUploader.on("file_added", function() {
                if (this.overlay.isOpen) {
                    this.overlay.close()
                }
            }, this);
            this.fileUploader.on("upload_complete", function(fileInfo) {
                this.editorRef.fireEvent("idisk_upload_complete", null, [fileInfo])
            }, this);
            this.fileUploader.on("remove_bucket", function(bucket) {
                this.editorRef.fireEvent("idisk_remove_file", null, [bucket])
            }, this)
        }};
    function IdiskOverlay(container, editorRef) {
        IdiskOverlay.superclass.call(this);
        var self = this;
        this.editorRef = editorRef;
        this.max_size = this.byte2str(option_editor.upload_max_size);
        this.$holder = $("<div>").attr("class", this.holderClass).css("left", "-1000px").html('<button id="' + this.uploadBtnId + '">上传文件</button><br>提示：选择文件按住Ctrl键可以选择多个文件<br>最多支持3个文件上传，单个文件大小限制在' + this.max_size + "之内。").append('<div class="close"></div>').find(".close").click(function() {
            self.onClose()
        }).end().append('<div class="arrow"></div>').appendTo(container);
        this.uploadBtn = this.$holder.find("button")[0]
    }
    extend(IdiskOverlay, EventDispatcher, {holderClass: "tb-editor-overlay idisk_holder",uploadBtnId: "idisk_btn",isOpen: false,onClose: function() {
            this.close()
        },close: function() {
            this.$holder.css("left", "-1000px");
            this.isOpen = false;
            this.fireEvent("close")
        },open: function() {
            if (TED.Editor.Status.isPicassoOpen === true) {
                var _this = this;
                var tips = $.dialog.confirm('<div id="maincontent" style="position:absolute;"><img style="margin:10px 10px 10px 10px;width:68px;height:68px;" src="http://static.tieba.baidu.com/tb/editor/v2/picasso/alarm.gif" /><div id="tipscontent" style="position:absolute;left:100px;top:15px;width:270px;font-size:14px;font-family:宋体" ><b>您正在编辑涂鸦，现在退出将不会保存，您确定要退出？</b></div></div>', {title: "涂鸦编辑器",acceptValue: "确定",cancelValue: "取消"});
                tips.width(420);
                tips.height(90);
                tips.bind("onaccept", function() {
                    TED.Editor.Status.isPicassoOpen = false;
                    _this.editorRef.overlay.close(true);
                    _this.$holder.css("visibility", "visible");
                    _this.isOpen = true;
                    _this.fireEvent("open")
                })
            } else {
                this.$holder.css("left", "230px");
                this.isOpen = true;
                this.fireEvent("open")
            }
        },toggle: function() {
            if (this.isOpen) {
                this.close()
            } else {
                this.open()
            }
        },byte2str: function(bytes) {
            bytes = parseInt(bytes);
            if (bytes < 1024) {
                return bytes + "byte"
            }
            var kb = (bytes / 1024).toFixed(2);
            if (kb < 1024) {
                return kb + "KB"
            }
            var mb = (kb / 1024).toFixed(2);
            if (mb < 1024) {
                return mb + "MB"
            }
            return (mb / 1024).toFixed(2) + "GB"
        }})
})();